package com.djq.hhc.listener;

import cn.hutool.json.JSONUtil;
import com.djq.hhc.model.shop.ShopOrder;
import com.djq.hhc.service.ShopOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Arrays;

import static com.djq.hhc.redis.RedisConstants.SHOP_ORDER_KEY;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: dadd7
 * @Date: 2023/04/06/下午 11:03
 * @Description:
 */
@Component
public class RedisKeyOrderExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyOrderExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ShopOrderService shopOrderService;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        if (key.startsWith(SHOP_ORDER_KEY)) {
            String json = stringRedisTemplate.opsForValue().get(key+":data");
            ShopOrder order = JSONUtil.toBean(json, ShopOrder.class);
            stringRedisTemplate.delete(key+":data");
            shopOrderService.orderPast(order);
        }
    }
}